import 'package:shared_preferences/shared_preferences.dart';

class SaveUtils {
  // 单例模式
  static SaveUtils? _instance;
  static SharedPreferences? _prefs;

  SaveUtils._();

  static Future<SaveUtils> getInstance() async {
    if (_instance == null) {
      _instance = SaveUtils._();
      await _instance!._init();
    }
    return _instance!;
  }

  Future<void> _init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// 保存数据
  static Future<bool?> setString(String key, String value) async {
    return await _prefs?.setString(key, value);
  }

  static Future<bool?> setInt(String key, int value) async {
    return await _prefs?.setInt(key, value);
  }

  static Future<bool?> setBool(String key, bool value) async {
    return await _prefs?.setBool(key, value);
  }

  static Future<bool?> setDouble(String key, double value) async {
    return await _prefs?.setDouble(key, value);
  }

  static Future<bool?> setStringList(String key, List<String> value) async {
    return await _prefs?.setStringList(key, value);
  }

  /// 获取数据
  static String getString(String key, {String defaultValue = ''}) {
    return _prefs?.getString(key) ?? defaultValue;
  }

  static int getInt(String key, {int defaultValue = 0}) {
    return _prefs?.getInt(key) ?? defaultValue;
  }

  static bool getBool(String key, {bool defaultValue = false}) {
    return _prefs?.getBool(key) ?? defaultValue;
  }

  static double getDouble(String key, {double defaultValue = 0.0}) {
    return _prefs?.getDouble(key) ?? defaultValue;
  }

  static List<String> getStringList(String key,
      {List<String> defaultValue = const []}) {
    return _prefs?.getStringList(key) ?? defaultValue;
  }

  /// 删除数据
  static Future<bool?> remove(String key) async {
    return await _prefs?.remove(key);
  }

  /// 清空所有数据
  static Future<bool?> clear() async {
    return await _prefs?.clear();
  }
}
